package middleware

import (
	"strings"

	"enterprise-base/internal/auth"

	"github.com/gin-gonic/gin"
)

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(200, gin.H{
				"code": 401,
				"msg":  "Unauthorized",
			})
			c.Abort()
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(200, gin.H{
				"code": 401,
				"msg":  "Invalid authorization header",
			})
			c.Abort()
			return
		}

		tokenString := parts[1]
		claims, err := auth.ParseJwtWithClaims(tokenString)
		if err != nil {
			c.JSON(200, gin.H{
				"code": 401,
				"msg":  "Invalid token",
			})
			c.Abort()
			return
		}

		c.Set("claims", claims)
		c.Next()
	}
}
